package org.example.postgraduateproject.Servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.postgraduateproject.Dao.UserDao;
import org.example.postgraduateproject.Dao.imp.UserDaoImp;
import org.example.postgraduateproject.entity.User;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bin
 * @date 2025-05-12
 */

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        PrintWriter out = resp.getWriter();

        String loginInfo = req.getParameter("loginInfo");
        String loginPass = req.getParameter("loginPass");

        UserDao userDao = new UserDaoImp();
        User user = null;

        // 记录登录信息类型
        String loginType = null;

        // 先检查用户名
        user = userDao.loginSelectUserName(loginInfo);
        if (user != null) {
            loginType = "username";
        } else {
            // 再检查手机号
            user = userDao.loginSelectPhone(loginInfo);
            if (user != null) {
                loginType = "phone";
            } else {
                // 最后检查邮箱
                user = userDao.loginSelectEmail(loginInfo);
                if (user != null) {
                    loginType = "email";
                }
            }
        }

        Map<String, Object> result = new HashMap<>();

        if (user == null) {
            // 用户不存在
            result.put("success", false);
            result.put("message", "用户不存在");
            result.put("errorCode", 1001);
        } else {
            if (user.getPassWord().equals(loginPass)) {
                // 登录成功
                result.put("success", true);
                result.put("message", "登录成功");
                result.put("user", user);
                result.put("loginType", loginType); // 返回登录类型
            } else {
                // 密码错误
                result.put("success", false);
                result.put("message", "密码错误");
                result.put("errorCode", 1002);
            }
        }

        Gson gson = new Gson();
        String json = gson.toJson(result);

        out.println(json);
        out.flush();
        out.close();
    }
}